<template>
  <div>
    <el-button class="btn" @click.native="backTop()" v-if="scrollTop>200">
      <i class="fa fa-caret-up" aria-hidden="true"></i>
    </el-button>
  </div>
</template>

<script>
export default {
  name: "BackToTop",

  data(){
    return{
      scrollTop: 0,
    }
  },
  methods: {
    // 点击图片回到顶部方法，加计时器是为了过渡顺滑
    backTop () {
      const that = this
      let timer = setInterval(() => {
        let ispeed = Math.floor(-that.scrollTop / 5)
        document.documentElement.scrollTop = document.body.scrollTop = that.scrollTop + ispeed
        if (that.scrollTop === 0) {
          clearInterval(timer)
        }
      }, 16)
    },

    scrollToTop () {
      const that = this
      let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
      that.scrollTop = scrollTop;
      console.log("scrollTop="+scrollTop);
    }
  },
  mounted() {
    window.addEventListener('scroll', this.scrollToTop)
  },
  destroyed () {
    window.removeEventListener('scroll', this.scrollToTop)
  },
}
</script>

<style scoped>
.btn{
  position: fixed;
  right: 40px;
  bottom: 40px;
}
</style>
